package com.jl.js.console;

import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.ui.console.IOConsole;

import com.jl.process.util.ExceptionTools;

public class DocChanged implements IDocumentListener{
	
	private IOConsole console;
	private int preLength;

	public DocChanged(IOConsole console){
		this.console = console;
	}

	@Override
	public void documentAboutToBeChanged(DocumentEvent event) {
		preLength = event.getOffset();
	}

	@Override
	public void documentChanged(DocumentEvent event) {
		String text = event.getText();
		if(text.contains(ExceptionTools.ERROR_TAG)){
			addExceptinHyperlink(text);
		}
		if(text.indexOf("load(") == 0){
			addLoadCmdHyperlink(text);
		}
	}

	private void addLoadCmdHyperlink(String text) {
		int begin = text.indexOf('(');
		int end = text.lastIndexOf(')');
		if(begin == -1 || end < begin){
			return;
		}
		String param = text.substring(begin,end);
		//FIXME : not implements
		String[] files = param.split(",");
		int offset = 0;
		for(String one : files){
			int index1 = one.indexOf('\'');
			int index2 = one.lastIndexOf('\'');
			if(index1 == -1){
				index1 = one.indexOf('\"');
				index2 = one.lastIndexOf('\"');
			}
			
			//String fullpath = FilePathUtil.getJSFilePath()
		}
	}

	private void addExceptinHyperlink(String text) {
		String[] lines = splitByLine(text);
		if(lines.length < 2){
			return;
		}
		int tagLine = -1;
		for (int i = 0; i < lines.length; i++) {
			if(lines[i].trim().equals(ExceptionTools.ERROR_TAG)){
				tagLine = i;
				break;
			}else{
				preLength += lines[i].length() + 1;
			}
		}
		if(tagLine == -1){
			return;
		}
		preLength += lines[tagLine++].length() + 1;
		preLength += lines[tagLine++].length() + 1;
		for (int i = tagLine; i < lines.length; i++) {
			if(lines[i].equals(">") || lines[i].contains("com.jl.smartcard.core\\config\\config.js")){
				preLength += lines[i].length() + 1;
				continue;
			}
			int index = lines[i].indexOf("at ") + 3;
			int endIndex = lines[i].indexOf(".js:");
			if(endIndex == -1){
				continue;
			}
			int endIndex2 = lines[i].lastIndexOf(" (");
			if(endIndex > endIndex2){
				endIndex2 = -1;
			}
			if(endIndex2 == -1){
				endIndex = lines[i].length();
			}else{
				endIndex = endIndex2;
			}
			
			try {
				console.addHyperlink(new JavaScriptHyberlink(console), preLength + index, endIndex - index);
				preLength += lines[i].length() + 1;
			} catch (BadLocationException e) {
				e.printStackTrace();
				return;
			}
		}
	}

	private String[] splitByLine(String text) {
		return text.split("(\n)");
	}

}
